package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {



    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;


    /**
     * 修改分类信息
     * 修改分类信息时如果修改了分类名称，那么所有与分类名称相关联的数据需要同步修改，比如品牌与分类关联表
     * @param category
     */
    @Transactional //开启事物
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.updateCascade(category.getName(),category.getCatId());
        }

    }

    /**
     * 查询分类的结构，根据子id查询所有父信息，调用递归方法查询父id是否还有父亲，有则继续查询，无则返回
     * @param attrGroup
     * @return
     */
    @Override
    public Long[] findByAttrId(Long catelogId) {

        List<Long> list = new ArrayList<>();
        //递归方法，查询子id所有父类信息
        List<Long> categoryLogPathId = findFatherid(catelogId, list);
        //查询出的数据倒叙
//        Collections.reverse(categoryLogPathId);
        return categoryLogPathId.toArray(new Long[categoryLogPathId.size()]);
    }

    private List<Long> findFatherid(Long catelogId, List<Long> list) {
        //根据子id查询出分类信息
        CategoryEntity logId = this.getById(catelogId);
        //如果分类信息的父id值不为0则代表该分类信息存在父类，继续递归查询
        if (logId.getParentCid() != 0) {
            findFatherid(logId.getParentCid(), list);
        }
        list.add(catelogId);
        return list;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
//        将查询出来的全部分类数据进行过滤，过滤条件为父类id为0的数据，
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) ->
                        categoryEntity.getParentCid() == 0)
                .map(menu -> {                //所以二级分类在进行分类
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .sorted((menu, menu2) -> {//排序
                    return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void deleteBatchIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }


    public List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> list = all.stream()
                .filter((categoryEntity) -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());

        return list;

    }


}